﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Tomahawk.Runtime.Canvas.Sprite
{
    /// <summary>
    /// A SpriteGroups represents an specialized use-case for sprite drawing.
    /// It manages the correct setting for the SpriteBatch, and the correct
    /// sorting and interation procedures for the sprites
    /// </summary>
    public abstract class SpriteRenderer : ICanvasPrimitiveRenderer
    {
        /// <summary>
        /// Stores the graphics device
        /// </summary>
        protected GraphicsDevice graphicsDevice;

        /// <summary>
        /// SpriteBatch used to render the sprites
        /// </summary>
        protected SpriteBatch spriteBatch;

        /// <summary>
        /// Constructor
        /// </summary>
        public SpriteRenderer()
        {
            this.sprites = new List<Sprite>();
        }

        /// <summary>
        /// Initialization
        /// </summary>
        public void Initialize(GraphicsDevice graphicsDevice)
        {
            //store the device
            this.graphicsDevice = graphicsDevice;

            //create the spritebatch
            spriteBatch = new SpriteBatch(graphicsDevice);
        }

        /// <summary>
        /// Let the child classes implement the rendering mechanism
        /// </summary>
        public abstract void Render();
      
        #region "Sprite management"

        /// <summary>
        /// List of sprite primitives to render
        /// </summary>
        protected List<Sprite> sprites;

        /// <summary>
        /// Add a primitive to the renderer
        /// </summary>
        public void AddPrimitive(ICanvasPrimitive newPrimitive)
        {
            Sprite sprite = newPrimitive as Sprite;
            if (sprite == null) throw new InvalidPrimitiveType(this, newPrimitive);
            sprites.Add(sprite);
            this.OnSpriteAdded(sprite);
        }

        /// <summary>
        /// Override this to provide specialized sprite addition
        /// </summary>
        protected virtual void OnSpriteAdded(Sprite newSprite)
        {
        }

        /// <summary>
        /// Remove a primitive from the renderer
        /// </summary>
        public void RemovePrimitive(ICanvasPrimitive primitive)
        {
            Sprite sprite = primitive as Sprite;
            if (sprite != null)
            {
                sprites.Remove(sprite);
                this.OnSpriteRemoved(sprite);
            }
        }

        /// <summary>
        /// Override this to provide specialized sprite removing
        /// </summary>
        protected virtual void OnSpriteRemoved(Sprite sprite)
        {
        }

        #endregion



    }

}
